package com.eurake.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eurake.seckill.Exception.GlobalException;
import com.eurake.seckill.mapper.OrderMapper;
import com.eurake.seckill.mapper.SeckillGoodsMapper;
import com.eurake.seckill.pojo.Order;
import com.eurake.seckill.pojo.SeckillGoods;
import com.eurake.seckill.pojo.SeckillOrders;
import com.eurake.seckill.pojo.User;
import com.eurake.seckill.service.IGoodsService;
import com.eurake.seckill.service.IOrderService;
import com.eurake.seckill.service.ISeckillGoodsService;
import com.eurake.seckill.service.ISeckillOrdersService;
import com.eurake.seckill.utils.MD5Util;
import com.eurake.seckill.vo.GoodsVo;
import com.eurake.seckill.vo.OrderDetailVo;
import com.eurake.seckill.vo.RespBeanEnum;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chen
 * @since 2024-11-24
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Resource
    SeckillGoodsMapper seckillGoodsMapper;

    @Resource
    ISeckillGoodsService seckillGoodsService;

    @Resource
    ISeckillOrdersService seckillOrdersService;

    @Resource
    RedisTemplate redisTemplate;

    @Resource
    OrderMapper orderMapper;

    @Resource
    IGoodsService goodsService;

    @Transactional
    @Override
    public Order seckill(User user, GoodsVo goodsVo) {
        SeckillGoods seckillGoods = seckillGoodsMapper.getSeckillGoodsById(goodsVo.getId());
        //库存减一
        seckillGoods.setStockCount(seckillGoods.getStockCount()-1);
        //更新数据库库存,解决超卖问题（一个货物被购买了多次）
        boolean seckillGoodsResult = seckillGoodsService.update(new UpdateWrapper<SeckillGoods>().
                setSql("stock_count=stock_count-1").eq( "id", seckillGoods.getId()).gt( "stock_count", 0));
        if(seckillGoods.getStockCount()<1){
            //判断是否还有库存
            redisTemplate.opsForValue().set("isStockEmpty:"+goodsVo.getId(), "0");
            return null;
        }
        //生成订单
        Order order = new Order();
        order.setUserId(user.getId());
        order.setGoodsId(goodsVo.getId());
        order.setDeliveryAddrId(0L);
        order.setGoodsName(goodsVo.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(seckillGoods.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());
        orderMapper.insert(order);

        //生成秒杀订单
        SeckillOrders seckillOrders = new SeckillOrders();
        seckillOrders.setUserId(user.getId());
        seckillOrders.setOrderId(order.getId());
        seckillOrders.setGoodId(goodsVo.getId());
        seckillOrdersService.save(seckillOrders);
        //解决超买问题，一个用户成功重复购买商品
        redisTemplate.opsForValue().set("order:" + user.getId()+":"+ goodsVo.getId(), seckillOrders);
        return order;
    }

    @Override
    public OrderDetailVo detail(Long orderId) {
        if (orderId == null) {
            throw new GlobalException(RespBeanEnum.ORDER_NOT_EXIST);
        }
        Order order = orderMapper.selectById(orderId);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(order.getGoodsId());
        OrderDetailVo detailVo = new OrderDetailVo();
        detailVo.setOrder(order);
        detailVo.setGoodsVo(goodsVo);
        return detailVo;
    }

    @Override
    public String createPath(User user, Long goodsId) {
        UUID uuid = UUID.randomUUID();
        String path = MD5Util.md5(uuid+"123456");
        redisTemplate.opsForValue().set("seckillPath:"+user.getId()+":"+ goodsId, path,60, TimeUnit.SECONDS);
        return path;
    }

    //校验秒杀地址
    @Override
    public boolean checkPath(String path, User user, long goodsId) {
        if(user==null||goodsId<0||path==null){
            return false;
        }
        String redisPath = (String)redisTemplate.opsForValue().get("seckillPath:"+user.getId()+":"+ goodsId);
        return path.equals(redisPath);
    }
}
